package com.alvin.mbp.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.alvin.mbp.entity.PointMember;
import com.alvin.mbp.entity.PointRecord;
import com.alvin.mbp.service.PointMemberService;
import com.alvin.mbp.service.PointRecordService;
import com.alvin.mbp.service.PointService;

@Controller
public class PointsAction {

	@Autowired
	private PointRecordService pointRecordService;

	@Autowired
	private PointMemberService pointMemberService;

	@Autowired
	private PointService pointService;

	@RequestMapping(value = "/points/charge.htm", method = RequestMethod.GET)
	public String charge(@RequestParam(value="icode", required=false) String icode, Model model) {
		if(icode != null){
			icode = icode.trim().replace(" ", "");
			Map<String, Object> qrMap = pointService.searchPointGoods(icode);
			model.addAttribute("qrMap", qrMap);			
		}
		
		return "/points/charge";
	}

	@RequestMapping(value = "/points/charge.htm", method = RequestMethod.POST)
	public String charge(Integer qrId, double qrPoint, String iCode, HttpServletRequest request) {

		PointMember member = (PointMember) request.getSession().getAttribute("MEMBER");
		boolean isSucc = pointService.charge(qrId, qrPoint, iCode, member);
		request.getSession().setAttribute("MEMBER", pointMemberService.findById(member.getId()));

		return "redirect:/message.htm?isSucc="+isSucc+"&icode="+iCode+"&qrPoint="+qrPoint;
	}
	
	@RequestMapping(value = "/message.htm", method = RequestMethod.GET)
	public String message(@RequestParam(value="isSucc", required=false) Boolean isSucc, @RequestParam(value="icode", required=false) String icode, @RequestParam(value="qrPoint", required=false) double qrPoint, Model model) {
		model.addAttribute("isSucc", isSucc);	
		model.addAttribute("icode", icode);	
		model.addAttribute("qrPoint", qrPoint);	
		return "/points/message";
	}

	@RequestMapping(value = "/points/chargeList.htm", method = RequestMethod.GET)
	public String chagreList(Model model, HttpServletRequest request) {

		PointMember member = (PointMember) request.getSession().getAttribute("MEMBER");
		List<PointRecord> records = pointRecordService.findByProperty("member_id", member.getId(), 10);
		model.addAttribute("records", records);
		return "/points/chargeList";

	}

}
